// base
import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import {
  DOREQUESTSELFCENTER,
  DOREQUESTRECOMMON,
  DOREQUESTCHANGECP
} from './store/actions/pageselfcenter'
import { UPDATEPAGESELFCENTER } from './store/types/pageselfcenter'
import { UPDATEIM } from '../../store/types/im'

// less
import './index.less'
import MyMessage from './components/my-message'
import PersonalInfo from './components/personal-info'
import JobsRecommended from './components/jobs-recommended'
// import GoFeedback from './components/go-feedback'
import If from '../../components/page-components/if'
import CompanyMessage from './components/company-message'
import JobPost from './components/job-post'
import CompanyCard from './components/company-card'
import VipCard from './components/vip-card'
import { UPDATEUSERINFO } from '../../store/types/userinfo'
import {
  getZhichuBUserInfo,
  getZhichuUserInfo,
  updateCompanyId
} from '../../store/actions/userinfo'
import { login } from '../../crossplatform/apiservice/login'
import { wxLoginRequest, refreshTokenRequest } from '../../service/login-controller'
import { postCenterNumbersRequest } from '../../service/user-controller'
import {
  getCompanyMessageRequest,
  clearCompanyMessageRequest
} from '../../service/company-controller'
import { showToast } from '../../crossplatform/apiservice/toast'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import { makePhoneCall } from '../../crossplatform/apiservice/makephonecall'
import Dialog from '../../components/page-components/dialog'
import { getStorageSync, removeStorageSync } from '../../crossplatform/apiservice/storage'
import IMController from '../../util/wy_im'
import { judgeLoginStatus } from '../../util/login_status'
import tool from '../../util/tool'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGESELFCENTER,
      payload: {
        ...payload
      }
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  dorequest({ userId }) {
    dispatch(DOREQUESTSELFCENTER({ userId })).then(({ payload: { archiveComplete } }) => {
      if (archiveComplete >= 0) {
        this.updateUserState({
          archiveComplete
        })
      }
    })
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  updateCompany() {
    dispatch(updateCompanyId())
  },
  queryRecommon(payload) {
    dispatch(DOREQUESTRECOMMON(payload))
  },
  queryCompanyInfo(payload) {
    return dispatch(DOREQUESTCHANGECP(payload))
  },
  getZhichuUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  getZhichuBUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuBUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pageselfcenter, userinfo, landmark, im }) => ({
    ...pageselfcenter,
    userId: userinfo.userId,
    zhichuUserId: userinfo.zhichuUserId,
    zhichuUserIdB: userinfo.zhichuUserIdB,
    companyId: userinfo.companyId,
    userInfoB: userinfo.userInfoB,
    userInfoC: userinfo.userInfoC,
    role: userinfo.role,
    companyName: userinfo.companyName,
    isVip: userinfo.isVip,
    accessToken: userinfo.accessToken,
    ...landmark,
    ...im
  }),
  mapActiontoProps
)
class SelfCenter extends Component {
  config = {}

  constructor(props) {
    super(props)
    this.state = {
      modalMessageVisible: false,
      modalMessage: [],
      modalData: {},
      postData: {},
      lastRole: ''
    }
  }

  componentWillMount() {
    // onLoad
    this.noticeIn()
    this.setState({
      timer: null
    })
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
    const { role, userId } = this.props
    this.doOnShow()
    this.doLogin()
    role === 'company' && IMController.notDeletedPostSession(userId)

    this.setState({
      modalMessageVisible: false
    })
  }

  componentWillUnmount() {
    const { timer } = this.state
    clearTimeout(timer)
  }

  componentWillReceiveProps(nextProps) {
    const { lastRole } = this.state
    if (lastRole != nextProps.role) {
      this.setState({
        lastRole: nextProps.role
      })
      // im登录
      this.imLogin()
    }
  }

  doLogin = ({ action } = {}) => {
    const { role, userId } = this.props
    if (role == 'company') {
      // 选择为招聘者
      if (!userId) {
        // 不存在userId肯定要去走登录
        this.goLoginFunc({ action })
      } else {
        this.tryGetUserInfo({ action, id: userId })
        // 去招聘者的详情
        if (action == 'click') {
          this.gotoMessageDetail()
        }
      }
    } else {
      // 选择为求职者
      if (!userId) {
        // 不存在userId肯定要去走登录
        this.goLoginFunc({ action })
      } else {
        this.tryGetUserInfo({ action, id: userId })
        // 去求职者的详情
        if (action == 'click') {
          this.gotoMessageDetail()
        }
      }
    }
  }

  onUploadAvator = tool.throttle(() => {
    judgeLoginStatus({ url: 'avator-page' })
  })

  gotoMessageDetail = tool.throttle(() => {
    const { role } = this.props
    if (role === 'personal') {
      judgeLoginStatus({ url: 'self-message' })
    } else {
      judgeLoginStatus({ url: 'company-represent-infor' })
    }
  })

  goLoginFunc = ({ action } = {}) => {
    login().then(({ code }) => {
      if (code) {
        wxLoginRequest({ code }).then(({ data = {} } = {}) => {
          const { code: codeToken } = data
          const { openId, userId, mobile, access_token: accessToken, refresh_token: refreshToken } =
            data.data || {}
          if (codeToken === 200) {
            this.props.updateUserState({
              openId,
              mobile: userId && mobile,
              accessToken,
              refreshToken,
              // zhichuUserId: userId,
              userId
            })
            if (userId) {
              // 存在anthUserId
              this.tryGetUserInfo({ action, id: userId })
            } else if (openId) {
              // 不存在
              if (action == 'click') {
                this.gotoMessageDetail()
              }
            } else {
              showToast({
                title: '网络走丢了'
              })
              // 不存在
              if (action == 'click') {
                this.gotoMessageDetail()
              }
            }
          } else {
            showToast({
              title: '网络走丢了~~'
            })
          }
        })
      } else {
        showToast({
          title: '网络走丢了'
        })
      }
    })
  }

  tryGetUserInfo = ({ action, id }) => {
    const { role } = this.props
    if (role == 'company') {
      this.getBUserInfo({ action, id })
    } else {
      this.getCUserInfo({ action, id })
    }
  }

  goSettingPage = () => {
    // 选择招聘者 跳转设置页
    const goSetting = getStorageSync('goSetting')
    if (goSetting) {
      removeStorageSync('goSetting')
      navigateTo({
        url: pagejumplist['setting-page'].path
      })
    }
  }

  getCUserInfo = ({ action, id }) => {
    const { userId } = this.props
    this.props.getZhichuUserInfo({ userId: id }).then(({ zhichuUserId }) => {
      if (zhichuUserId) {
        // showToast({
        //   title: '登录成功！'
        // })
        // 获取详细信息
        this.personalInfoRef.getData(userId)
        this.doOnShow()
      } else {
        // showToast({
        //   title: '网络走丢了'
        // })
        this.props.updateUserState({
          userId: id
        })
        if (action == 'click') {
          this.gotoMessageDetail()
        }
      }
    })
  }

  getBUserInfo = ({ action, id }) => {
    this.props.getZhichuBUserInfo({ userId: id }).then(({ zhichuUserIdB }) => {
      if (zhichuUserIdB) {
        // showToast({
        //   title: '登录成功！'
        // })
        this.doOnShow()
      } else {
        // showToast({
        //   title: '网络走丢了'
        // })
        this.props.updateUserState({
          userId: id
        })
        if (action == 'click') {
          this.gotoMessageDetail()
        }
      }
    })
  }

  doOnShow = () => {
    this.queryWrap()
    this.tryAsyncCompanyId()
    this.queryRecommon({ city: this.props.landmarkName })
  }

  tryAsyncCompanyId = () => {
    // b的userId role为company 且没有公司Id时尝试去同步公司id
    const { role, userId } = this.props
    if (role == 'company' && userId) {
      this.props.updateCompany()
    }
  }

  queryWrap = () => {
    // 同步用户信息
    const { role, companyId, userId } = this.props
    if (role == 'company' && userId && companyId) {
      this.getCompanyMessage()
      this.getZCollectionCount()
      this.props
        .queryCompanyInfo({ companyId })
        .then(({ payload: { status, entry, message, memberType, postData } }) => {
          if (status) {
            this.props.updateUserState({
              isVip: !!entry,
              memberType
            })
            this.setState({
              postData
            })
          } else {
            showToast({
              title: message || 'queryCompanyInfo失败'
            })
          }
        })
    } else {
      if (userId) {
        this.getUserMessage({ id: userId })
      }
    }
  }

  getUserMessage = ({ id }) => {
    // let timer = setTimeout(() => {
    //   clearTimeout(timer)
    //   this.props.dorequest({ userId: id })
    // }, 1000)

    let type = 'C'
    const { role } = this.props
    type = role == 'personal' ? 'C' : 'B'
    postCenterNumbersRequest({ type }).then(({ data }) => {
      const { status, message, entry } = data
      if (status) {
        this.props.updateState({
          collectCount: entry.postCollection || 0
        })
      } else {
        showToast({
          title: message || '获取人才收藏数据失败'
        })
      }
    })
  }

  getZCollectionCount = () => {
    let type = 'C'
    const { role } = this.props
    type = role == 'personal' ? 'C' : 'B'
    postCenterNumbersRequest({ type }).then(({ data }) => {
      const { status, message, entry } = data
      if (status) {
        this.props.updateState({
          ZcollectCount: entry.archiveCollection,
          ZmanageCount: entry.post,
          ZtalentTalk: entry.talentTalk,
          postException: entry.un_look_exception_post // TODO 应该是未读消息
        })
      } else {
        showToast({
          title: message || '获取人才收藏数据失败'
        })
      }
    })
  }

  onChangeRole = () => {
    showToast({
      title: '您还没有归属的公司哦～'
    })
  }

  queryRecommon = ({ city }) => {
    let submitdata = {
      page: 1,
      pageSize: 10,
      postSearchCondition: {
        anyWhere: 0,
        area: [],
        category: [],
        education: 0,
        settlementMethod: [],
        type: []
      },
      city
    }
    this.props.queryRecommon({ ...submitdata })
  }

  jumpToVip = () => {
    navigateTo({
      url: `${pagejumplist['vip-pay'].path}`
    })
  }

  callphone = () => {
    makePhoneCall({ phoneNumber: '4001616661' })
  }

  onNoVip = () => {
    // 非vip跳转页面
    navigateTo({
      url: `${pagejumplist['vip-recharge'].path}`
    })
  }

  onVip = () => {
    // vip跳转页面
    navigateTo({
      url: `${pagejumplist['vip-center'].path}`
    })
  }

  goOrderList = () => {
    // 跳转订单管理页面
    navigateTo({
      url: `${pagejumplist['order-list'].path}`
    })
  }

  getCompanyMessage = () => {
    // 获取公司消息
    getCompanyMessageRequest().then(({ data }) => {
      const { status, entry, message } = data
      if (status) {
        if (entry.length) {
          let modalData = {}
          let modalMessage = entry[0]
          const { type } = modalMessage
          switch (parseInt(type)) {
            case 0:
              modalData.title = '岗位下架提示'
              modalData.desc = `您的岗位${modalMessage.postName}因${modalMessage.refuseNote}平台已下架该岗位,请修改后重新上传`
              modalData.leftText = '关闭提示'
              modalData.rightText = '修改岗位'
              break
            case 1:
              modalData.title = '岗位驳回提示'
              modalData.desc = `您的岗位${modalMessage.postName}因${modalMessage.refuseNote}原因被驳回上架,请修改后重新上传`
              modalData.leftText = '关闭提示'
              modalData.rightText = '修改岗位'
              break
            case 2:
              modalData.title = '岗位审核通过提示'
              modalData.desc = `您的岗位${modalMessage.postName}已经通过平台审核`
              modalData.leftText = '关闭'
              modalData.rightText = '确认'
              break
          }
          this.setState({
            modalMessage,
            modalData
          })
          let timer = setTimeout(() => {
            clearTimeout(timer)
            this.setState({
              modalMessageVisible: true
            })
          }, 500)
        }
      } else {
        showToast({
          title: message || '获取消息失败'
        })
      }
    })
  }

  onCloseMessage = () => {
    // 点击遮罩
    this.setState({
      modalMessageVisible: false
    })
  }

  onClearMessage = () => {
    // 点击关闭提示
    const { companyId } = this.props
    clearCompanyMessageRequest({ companyId }).then(({ data }) => {
      const { status, message } = data
      if (status) {
      } else {
        showToast({
          title: message || '删除消息失败'
        })
      }
      this.setState({
        modalMessageVisible: false
      })
    })
  }

  onEditJob = () => {
    // 修改岗位, 跳转岗位管理页
    const {
      modalMessage: { type }
    } = this.state
    const { postException } = this.props
    if (type) {
      this.onClearMessage()
      navigateTo({
        url: `${pagejumplist['manage-jobs'].path}?postException=${postException}`
      })
    } else {
      this.onCloseMessage()
    }
    this.setState({
      modalMessageVisible: false
    })
  }

  refPersonalInfo = node => (this.personalInfoRef = node)

  noticeIn = () => {
    // 通过推送消息进入该页面 (公司审核通过)
    const { role = '' } = this.$router && this.$router.params

    if (role == 'company') {
      this.props.updateUserState({
        role: 'company'
      })
    }
  }

  imLogin = () => {
    // im登录
    IMController.queryWrap()
  }

  updateJobStatus = jobStatus => {
    this.props.updateState({
      jobStatus
    })
  }

  render() {
    const {
      ZtalentTalk,
      ZcollectCount,
      ZmanageCount,
      companyName,
      userInfoB,
      collectCount,
      companyId,
      userInfoC,
      zhichuUserIdB,
      role,
      userName,
      viewCounts,
      shareCounts,
      userAvator,
      postException,
      jobStatus,
      memberType
    } = this.props
    const { modalMessageVisible, modalData, postData } = this.state

    return (
      <View className="SelfCenter_id34889">
        <If visible={role == 'personal' || !companyId}>
          <MyMessage
            role={role}
            collectCount={collectCount}
            userInfoB={userInfoB}
            userInfoC={userInfoC}
            viewCounts={viewCounts}
            shareCounts={shareCounts}
            onQueryWrap={this.queryWrap}
            onChangeRole={this.onChangeRole}
            onGoLogin={this.gotoMessageDetail}
            onUploadAvator={this.onUploadAvator}
          />
        </If>
        <If visible={role == 'personal' || !companyId}>
          <PersonalInfo
            ref={this.refPersonalInfo}
            jobStatus={jobStatus}
            onUpdateJobStatus={this.updateJobStatus}
          />
        </If>
        <If visible={role == 'personal' || !companyId}>
          <JobsRecommended dataSource={this.props.dataSourceRecommon} />
        </If>
        <If visible={role == 'company' && companyId}>
          <CompanyMessage
            ZtalentTalk={ZtalentTalk}
            ZcollectCount={ZcollectCount}
            ZmanageCount={ZmanageCount}
            userName={userName}
            userAvator={userAvator}
            onQueryWrap={this.queryWrap}
            onGoLogin={this.gotoMessageDetail}
            postException={postException}
            onUploadAvator={this.onUploadAvator}
          />
        </If>
        <If visible={role == 'company' && companyId}>
          <JobPost
            companyId={companyId}
            zhichuUserIdB={zhichuUserIdB}
            onChangeRole={this.onChangeRole}
            postData={postData}
          />
        </If>
        <If visible={role == 'company' && companyId}>
          <VipCard
            memberType={memberType}
            vipData={this.props.isVip}
            onNoVip={this.onNoVip}
            onVip={this.onVip}
          />
        </If>
        <If visible={role == 'company' && companyId}>
          <CompanyCard
            companyName={companyName}
            zhichuUserIdB={zhichuUserIdB}
            onChangeRole={this.onChangeRole}
          />
        </If>

        <If visible={role == 'company' && companyId}>
          <View className="feedback" onClick={this.goOrderList}>
            <View className="name">
              订单记录
              <View className="name-sub">查询订单记录</View>
            </View>
            <Image
              className="imgright"
              src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
            />
          </View>
        </If>

        <View className="feedback" onClick={this.callphone}>
          <View className="name">
            意见反馈
            <View className="name-sub">欢迎积极反馈意见 400-161-6661</View>
          </View>
          <Image
            className="imgright"
            src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
          />
        </View>

        <AtActionSheet isOpened={modalMessageVisible}>
          <Dialog
            title={modalData.title}
            subtext={modalData.desc}
            leftText={modalData.leftText}
            rightText={modalData.rightText}
            onOk={this.onEditJob}
            onLeftOk={this.onClearMessage}
          />
        </AtActionSheet>
      </View>
    )
  }
}

export default SelfCenter
